package com.ruike.alisurface.ui.payPage;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.OrderrBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.http.OtherApiHttp;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.http.OtherApiHttp.EXPIRE_CREATE_ORDER_URL;

/**
 * Author: voodoo
 * CreateDate: 2020-04-08
 * Description: 扫码页
 */
public class PayForQRCodeActivity extends BaseAty {

    @BindView(R.id.titleBar_titleIco_imgv)
    ImageView titleBarTitleIcoImgv;
    @BindView(R.id.titleBar_appVersion_tv)
    TextView titleBarAppVersionTv;
    @BindView(R.id.titleBar_setting_view)
    View titleBarSettingView;
    @BindView(R.id.titleBar_root_rlayout)
    RelativeLayout titleBarRootRlayout;

    @BindView(R.id.alchatPay_goBack_imgv)
    ImageView alchatPayGobackImgv;
    @BindView(R.id.alchat_zxing_code)
    ImageView alchatZxingCode;
    @BindView(R.id.alchat_zxing_price)
    TextView aliZxingPrice;
    @BindView(R.id.alchat_zxing_count_time)
    TextView aliZxingCountTime;

    String OrderNO;
    Bitmap bitmap;
    Timer paytimer;
    TimerTask timerTask;
    Timer createOrderHttpTimer; // 创建订单的计时器

    List<CarGoodsBeans> paycarlist;//购物车集合
    double money = 0.00f;//总金额
    OrderrBean orderrBean;//订单类
    ShopDetailBean shopDetailBean;//商品详情类
    CustomDialog dialog;//弹窗
    AlertDialog alertDialog;//提示框

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_wealchat;
    }

    @Override
    protected void initViews() {
        L.i("扫码支付页==" + this.getClass().getName());
        initTitleBar(false);
        // 返回按钮不可点击
        alchatPayGobackImgv.setEnabled(false);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(300, aliZxingCountTime, null);

        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        if (paycarlist == null) {
            L.i("查询商品数据异常");
            showErrorTip("查询商品数据异常");
            startCountdownTimer(3, null, null);
            return;
        }
        showcodeAlt(); // 创建订单
        L.iTag("排错", "查询到数据库商品对象：" + paycarlist);

        new CountDownTimer(2000, 2000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                alchatPayGobackImgv.setEnabled(true);
            }
        }.start();

    }

    @OnClick({R.id.alchatPay_goBack_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.alchatPay_goBack_imgv:
                L.i("返回按钮点击");
                gobackTip();
                break;
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        L.i("requestUrl==" + requestUrl);
        if (EXPIRE_CREATE_ORDER_URL.equals(requestUrl) || requestUrl.endsWith("create") || requestUrl.endsWith("CreateForProduct")) {
            L.iTag("排错", "下单返回数据：" + requestJsonStr);
            cancelCreateOrderHttpTimer();
            // 获取商品支付信息
            orderrBean = GsonUtils.json2Model(requestJsonStr, OrderrBean.class);
            String zxinurl = orderrBean.getData().getUrl();
            OrderNO = orderrBean.getData().getId();
            aliZxingPrice.setText(String.format(Locale.ENGLISH, "%.2f", orderrBean.getData().getTotal_fee()));
            bitmap = ZXingUtils.getInstance().createQRImage((zxinurl), 500, 500, BitmapFactory.decodeResource(getResources(), 0));
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            alchatZxingCode.setImageBitmap(bitmap);

            shopDetailBean = new ShopDetailBean(OrderNO);
            shopDetailBean.setPromotion_fee(-1);
            money = orderrBean.getData().getTotal_fee();
            shopDetailBean.setTotal_fee(money);
            shopDetailBean.setPay_fee(money);

            List<ShopDetailBean.OrderDetailsBean> orderDetailsBeanList = new ArrayList<>();
            List<OrderrBean.DataBean.DetailsBean> detailsList = orderrBean.getData().getDetails();
            for (int i = 0; i < detailsList.size(); i++) {
                ShopDetailBean.OrderDetailsBean tempDetailBean = new ShopDetailBean.OrderDetailsBean();
                OrderrBean.DataBean.DetailsBean detailsBean = detailsList.get(i);
                tempDetailBean.setSlotIndex(detailsBean.getSlotIndex());
                tempDetailBean.setQuantity(detailsBean.getQuantity());
                tempDetailBean.setSlotTypeId(detailsBean.getSlotTypeId());
                orderDetailsBeanList.add(tempDetailBean);
            }

            L.iTag("排错", "出货列表数据：" + orderDetailsBeanList);

            shopDetailBean.setDetailOrderList(orderDetailsBeanList);

            startTimer();

        } else if (requestUrl.endsWith("getPayResult")) {
            JSONObject object = null;
            try {
                object = new JSONObject(requestJsonStr);
                int code = object.optInt("code");
                L.i("getPayResult==" + requestJsonStr);
                if (code == 0) {
                    setCanal();
                    String order_code = ShareUtils.getInstance().getString(ShareKey.ORDER_RESULT, "");
                    L.iTag("支付页==order_code= ", "上次的单号==" + order_code + "==");
                    if (!TextUtils.isEmpty(order_code) && shopDetailBean != null && order_code.equals(shopDetailBean.getOrderId())) {
                        L.iTag("支付页==order_code= ", "这次的单号=="
                                + shopDetailBean.getOrderId() + "==" + "多次出 货，订单号已经出货过 无法再次出货 回到主页面");
                        BackMainUtils.setActivity(this);
                        finish();
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("pay_type", "noFace");
                    bundle.putSerializable("orderBeanData", shopDetailBean);
                    startActivity(PayShowShopActivity.class, bundle);
                    finish();
                } else {
                    L.i("getPayResult" + "==等待支付=");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("getPayResult")) {
            L.e(requestUrl + "==onError=" + errorMsg, "---等待支付--");
        } else if (requestUrl.endsWith("create")) {
            cancelCreateOrderHttpTimer();
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            L.e(requestUrl + "=onError==" + errorMsg);
            showErrorTip(errorMsg);

        } else if (requestUrl.endsWith("CreateForProduct")) {
            cancelCreateOrderHttpTimer();
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            L.e(requestUrl + "=onError==" + errorMsg);
            showErrorTip(errorMsg);
        }
    }

    public void gobackTip() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_qrcode_goback, null, false);
        dialogView.findViewById(R.id.qrcodeGobackDialog_cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialogView.findViewById(R.id.qrcodeGobackDialog_ok_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startCountdownTimer(0, null, null);
            }
        });

        dialog = new CustomDialog.Builder(this)
                .setContentView(dialogView)
                .create();
        dialog.show();
    }


    /**
     * 生成二维码提示框
     */
    private void showcodeAlt() {
        try {
            showProgressDialog("正在生成二维码加载数据，请稍后......", false);
            createOrderHttpTimer = new Timer();
            createOrderHttpTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(() -> {
                        showErrorTip("数据返回异常，请重新尝试购买");
                        startCountdownTimer(2, null, null);
                    });
                }
            }, 30_000);
//            if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
//                L.i("按货道展示上传信息");
//                getPayinfoCode();
            OtherApiHttp.expireCreateOrder(paycarlist.get(0).getProductid(), this);
//            } else {
//                L.i("按商品类型展示上传信息");
//                getPayTypeinfoCode();
//            }
        } catch (Exception e) {
            L.i("pay====error==", e.getLocalizedMessage());
        }
    }

    /**
     * 按货道下单
     */
    public void getPayinfoCode() {
        try {
            // 判断数据是否已经存在
            String result = "";
            for (int i = 0; i < paycarlist.size(); i++) {
                result += paycarlist.get(i).getSlotIndexs() + ",";
            }
            Map<String, Integer> map;
            List list1 = new ArrayList();
            //将字符串转化为字符数组
            String[] chars = result.split(",");
            //创建一个HashMap名为hm
            HashMap<String, Integer> hm = new HashMap();
            //定义一个字符串c，循环遍历遍历chars数组
            for (String c : chars) {
                if (!hm.containsKey(c)) {
                    hm.put(c, 1);
                } else {
                    //否则获得c的值并且加1
                    hm.put(c, hm.get(c) + 1);
                }
                //或者上面的if和else替换成下面这一行
                /*  hm.put(c,hm.containsKey(c) ? hm.get(c)+1:1);*/
            }
            //上传商品详情 去的订单号 显示成二维码
            for (String key : hm.keySet()) {
                map = new HashMap<>();
                //hm.keySet()代表所有键的集合,进行格式化输出
                map.put("Quantity", hm.get(key));
                map.put("SlotIndex", Integer.parseInt(String.valueOf(key)));
                list1.add(map);
            }

            HashMap<String, Object> maps = new HashMap<>();
            maps.put("mchId", ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
            maps.put("OrderDetails", GsonUtils.list2JsonArrayNotNulls(list1));
            maps.put("IsFace", false);
            MchApiHttp.postGoodsQRCode(this, maps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 按类型下单
     */
    public void getPayTypeinfoCode() {
        try {
            //判断数据是否已经存在
            Map<String, Object> map;
            List list1 = new ArrayList();
            //上传商品详情 去的订单号 显示成二维码
            for (int i = 0; i < paycarlist.size(); i++) {
                map = new HashMap<>();
                map.put("Quantity", 1);
                map.put("productid", paycarlist.get(i).getProductid());
                List<Integer> slotIndexs = new ArrayList<>();
                L.i("slotIndexs====", paycarlist.get(i).getSlotIndexs());
                JSONArray jsonArray = new JSONArray(paycarlist.get(i).getSlotIndexs());
                for (int c = 0; c < jsonArray.length(); c++) {
                    slotIndexs.add(Integer.parseInt(jsonArray.opt(c) + ""));
                }
                map.put("slotIndexs", slotIndexs);
                list1.add(map);
            }
            HashMap<String, Object> maps = new HashMap<>();
            maps.put("mchid", ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
            maps.put("OrderDetails", GsonUtils.list2JsonArrayNotNulls(list1));
            MchApiHttp.postGoodsTypeQRCode(this, maps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void startTimer() {
        setCanal();
        paytimer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                MchApiHttp.getPayResult(PayForQRCodeActivity.this, OrderNO);
            }
        };
        paytimer.schedule(timerTask, 10, 3000);
    }

    public void setCanal() {
        if (timerTask != null) {
            L.i("==setCanal=取消计时=timerTask=" + timerTask);
            timerTask.cancel();
            timerTask = null;
        }
        if (paytimer != null) {
            L.i("==setCanal=取消计时=paytimer" + paytimer);
            paytimer.cancel();
            paytimer = null;
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals("计时结束") && event.getMessage().equals("查询订单倒计时结束")) {
            sendOrderStatus(1);
        }
    }

    /**
     * 上传订单是否超时
     */
    public void sendOrderStatus(int sign_order_state) {
        if (!TextUtils.isEmpty(OrderNO)) {
            MchApiHttp.sendSign_order(OrderNO, sign_order_state, PayForQRCodeActivity.this);
        }
    }

    private void cancelCreateOrderHttpTimer() {
        if (createOrderHttpTimer != null) {
            createOrderHttpTimer.cancel();
            createOrderHttpTimer = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.i("==onDestroy==");
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog = null;
        }
        MchApiHttp.cancalpayResult();
        setCanal();
        if (bitmap != null) {
            alchatZxingCode.setImageBitmap(null);
            bitmap.recycle();
            bitmap = null;
        }
        if (alertDialog != null) {
            alertDialog.dismiss();
            alertDialog = null;
        }
        cancelCreateOrderHttpTimer();
    }

}
